﻿

//--全局授权登录验证拦截  --拦截全局过滤器中的返回值
//ajax执行成功后的回调
//$(document).ajaxSuccess(function (event, xhr, setting, response) {
//    if (setting.type=="POST") {//POST请求没有转成json
//           response = eval('(' + response + ')');
//    }
//    debugger;
//    if (response.code == 400) {//登录状态失效
//        ShowError(response.msg);
//        location.href = "/Account/Login";
//        return;
//    }
//    if (response.code == 401) {//没有权限
//        ShowError(response.msg);
//        return;
//    }

//});
//ajax执行失败时后的回调
//$(document).ajaxError(function (event, xhr, setting, response) {
//    var errorUrl = setting.url;

//    if (response == "Not Found" || response == "") {
//        return;
//    }
//    ShowError("url【" + errorUrl + "】发生了未知异常，请联系管理员");
//});

function ShowError(msg) {
    $.gritter.add({
        title: "错误提示",
        text: msg,
        time: 1500,
        class_name: 'gritter-error'
    });
}
function ShowInfo(msg) {
    $.gritter.add({
        title: "消息提示",
        text: msg,
        time: 1500,
        class_name: 'gritter-info'
    });
}
function ShowSuccess(msg) {
    $.gritter.add({
        title: "成功提示",
        text: msg,
        time:1500,
        class_name: 'gritter-success'
    });
}
//移除选项卡
function removeTab(obj) {
    var $nav = $(obj).parent().parent();//选项卡
    var $content = $($(obj).parent().attr("href"));//内容
    if ($nav.prev().length == 0) {//第一个不能删除
        return;
    }
    if ($nav.hasClass("active")) {
        $nav.prev().addClass("active");
        $content.prev().addClass("active").addClass("in");
    }
    $nav.remove();
    $content.remove();
}
function ajaxGet(url, target, callbackFunction, dataType) {
	$.ajaxSetup({ cache: false }); 
    if (dataType == undefined || dataType == null || dataType == "") {
        dataType = "html";
    }
    $.ajax({
        url: url,
        dataType: dataType,
        async: true,
        data: null,
        type: "GET",
        beforeSend: function (xMLHttpRequest) {
        },
        success: function (response, status) {
            if (dataType == "html") {
                if (response.match("^\{(.+:.+,*){1,}\}$")) {
                    response = eval('(' + response + ')');
                    if (response.code == 400 || response.code == 401 || response.code == 500) {
                        ShowError(response.msg);
                        if (response.code == 400) {
                            location.href = "/Account/Login";
                        }
                        return;
                    }
                }
            }
            if (dataType == "json") {
                if (response.code == 400 || response.code == 401 || response.code == 500) {
                    ShowError(response.msg);
                    if (response.code == 400) {
                        location.href = "/Account/Login";
                    }
                    return;
                }

            }


            if (target != undefined && target != null) {
                target.html(response);

            }
            if (callbackFunction != undefined) {
                callbackFunction(response);
            }
        },
        complete: function (xMLHttpRequest) {
        },
		error: function (xMLHttpRequest) {
			if (xMLHttpRequest.status == 404) {
				ShowError("404错误：请求的URL不存在");
			} else {
				ShowError("请求发生了未知异常，请联系管理员");
			}
           
            debugger;
        }
    });
}
function ajaxPost(url, data, callbackFunction) {
	$.ajaxSetup({ cache: false }); 
    $.ajax({
        url: url,
        dataType: "json",
        async: true,
        data: data,
        type: "POST",
        beforeSend: function (xMLHttpRequest) {
        },
        success: function (response) {
            if (response.code == 400 || response.code == 401 || response.code == 500) {
                ShowError(response.msg);
                if (response.code == 400) {
                    location.href = "/Account/Login";
                }
                return;
            }
            if (callbackFunction != undefined) {
                callbackFunction(response);
            }
        },
        complete: function (xMLHttpRequest) {
        },
        error: function (xMLHttpRequest) {
			if (xMLHttpRequest.status == 404) {
				ShowError("404错误：请求的URL不存在");
			} else {
				ShowError("请求发生了未知异常，请联系管理员");
			}
            debugger;
        }
    });
}
//加载左侧菜单
function loadTwoMenu(url) {
    var parentId = $(".first-menu.active").attr("node-id");
    ajaxGet(url+"?parentId=" + parentId, $(".two-menu-all"));

}
//加载右侧内容
function loadContent(obj) {
    var $this = $(obj);
    var parentid = $this.attr("tab-parentid");
    $(".two-menu-all").find("li").removeClass("active").removeClass("open");
    $this.parent().addClass("active");
    $(".two-menu-" + parentid).addClass("active").addClass("open");
    var id = $this.attr("tab-id");
    var name = $this.attr("tab-name");
    var url = $this.attr("tab-url");
    $("#mainTab").children().removeClass("active");
    $("#mainTabContent").children().removeClass("active").removeClass("in");

    var currentTab = $("#mainTab").find("li a[href='#" + id + "']");
    if (currentTab.length > 0) {//存在
        currentTab.parent().addClass("active");
        $("#mainTabContent").find("div[id=" + id + "]").addClass("active").addClass("in");
    }
    else {
        $("#mainTab").append("<li class='active'><a data-toggle='tab' href='#" + id + "' aria-expanded='true'>" + name + "<i class='fa fa-remove nva-tab-remove' onclick='removeTab(this)'></i></a> </li>");
        $("#mainTabContent").append("<div id='" + id + "' class='tab-pane fade in active' first-url='" + url + "'></div>");

    }
    ajaxGet(url, $("#" + id));



}

//初始化UI
var InitUI = function () {
	$.ajaxSetup({ cache: false }); 
    $(document).on("click", ".btnSearch", function () {
        $("#mainTabContent div.active").find("#pageIndex").val(1);
        LoadPageBar($("#mainTabContent div.active").find("#formSearch").attr("call-url"), "Pagination", 0, $("#mainTabContent div.active"));
    });
    $(document).on("click", ".btnRefresh", function () {
        var href = $("#mainTabContent div.active").attr("first-url");
		
		ajaxGet(href, $("#mainTabContent div.active"));
    });
    //编辑
    $(document).on("click", ".popupEdit", function () {
        var title = $(this).attr("title");
        var calltype = $(this).attr("call-type");
        var callurl = $(this).attr("call-url");
		var callbackurl = $(this).attr("callback-url");
		debugger;
        popupEdit(title, calltype, callurl, callbackurl);
    });

    $(document).on("click", ".popupConfirm", function () {
        var title = $(this).attr("title");
        var callurl = $(this).attr("call-url");
        var callbackurl = $(this).attr("callback-url");
        popupComfirm(title, callurl, callbackurl);

	});
	$(document).on("click", ".goSecondPage", function () {
		var title = $(this).attr("title");
		var callurl = $(this).attr("call-url");
		var callbackurl = $(this).attr("callback-url");
		goSecondPage(title, callurl, callbackurl);

	});
	$(document).on("click", ".goFirstPage", function () {
		goBackFirstPage();
	});

};



function popupEdit(title, calltype, callurl, callbackurl) {
    ajaxGet(callurl, null, function (response) {
        bootbox.dialog({
            message: response,// dialog的内容
            title: title, // dialog的标题
            onEscape: function () {// 退出dialog时的回调函数，包括用户使用ESC键及点击关闭

            },
            show: true, // 是否显示此dialog，默认true
            //backdrop: true, // 是否显示body的遮罩，默认true
            closeButton: true,  // 是否显示关闭按钮，默认true
            animate: true, // 是否动画弹出dialog，IE10以下版本不支持
            className: "my-modal", // dialog的类名

            // dialog底端按钮配置
            buttons: {

                // 其中一个按钮配置
                success: {
                    // 按钮显示的名称
                    label: "<i class='fa fa-check'></i> 确定",
                    // 按钮的类名
                    className: "btn-success",

                    // 点击按钮时的回调函数
                    callback: function () {
                        var currentBox = $(this);
                        var form = currentBox.find("form");
                        var url = form.attr("action");
                        var arr = form.serialize();
                        ajaxPost(url, arr, function () {
                            ShowSuccess("操作成功");
                            if (calltype == "add") {
								//整个页面刷新
								ajaxGet(callbackurl, $("#mainTabContent div.active"));
                            }
                            if (calltype == "edit") {
                                //列表刷新
                                LoadPageBar(callbackurl, "Pagination", $("#mainTabContent div.active").find("#pageIndex").val() - 1, $("#mainTabContent div.active"));
                            }
                            if (calltype == "noRefresh") {
                                //不刷新页面
							}
							if (calltype == "window") {
								//url重定向
								window.location.href = callbackurl;
							}
                            //模拟点击关闭按钮，关闭弹窗
                            currentBox.find("button[data-bb-handler=close]").click();
                        });

                        return false;//阻止弹窗消失
                    }
                },

                // 另一个按钮配置
                close: {
                    label: "<i class='fa fa-remove'></i> 关闭",
                    className: "btn-default",
                    callback: function () { }
                }
            }
        });
    });
   

}
function popupComfirm(title, callurl, callbackurl) {
    bootbox.confirm({
        message: title,
        buttons: {
            confirm: {
                label: "确定",
                className: "btn-primary btn-sm",
            },
            cancel: {
                label: "取消",
                className: "btn-sm",
            }
        },
        callback: function (result) {
            if (result) {
                ajaxGet(callurl, null, function () {
                    ShowSuccess("操作成功");
                    LoadPageBar(callbackurl, "Pagination", $("#mainTabContent div.active").find("#pageIndex").val() - 1, $("#mainTabContent div.active"));
                },"json");
           
            }
        }
    }
    );

}

function goSecondPage(title, callurl, callbackurl) {
	var container = $("#mainTabContent div.active");
	container.attr("second-url", callurl);
	container.attr("backto-first-url", callbackurl);
	ajaxGet(callurl, container);
}

function goBackFirstPage() {
	var container = $("#mainTabContent div.active");
	container.removeAttr("second-url");
	var backurl = container.attr("backto-first-url");
	container.removeAttr("backto-first-url");
	ajaxGet(backurl, container);
}

//分类加载完毕的回调
function backtoPrePage(url, callBackFunction) {
	try {
		var arr = getParasArr(url);
		for (var key in arr) {
			var value = arr[key];
			$("#" + key).val(value);
			if ($("select[name=" + key + "]").children().length > 0) {
				$("select[name=" + key + "]").children("option[value=" + value + "]").attr("selected", "selected");
			}
		}
		if (callBackFunction != undefined) {
			callBackFunction();
		}
		

	} catch (e) {
		callBackFunction();
	}

}
//获取url参数返回字典
function getParasArr(url) {
	try {
		if (url.indexOf("?") == -1) {
			return new Array();
		}
		var arr = new Array();
		var str = url.substr(url.indexOf("?") + 1);
		str = decodeURI(str);
		str = decodeURIComponent(str);
		var arr = str.split("&amp;");
		for (var i = 0; i < arr.length; i++) {
			var pa = arr[i];
			var dic = pa.split("=");
			var key = dic[0];
			var value = dic[1];
			arr[key] = value;

		}
		return arr;
	}
	catch (ex) {

	}
}